

const formatTime = (num) => {
    num = num.toFixed(0);
    let second = (num % 60);
    if (second < 10) {
        second = '0' + second
    }
    let min = Math.floor(num / 60);
    if (min < 10) {
        min = '0' + min
    }
    return `${min}:${second}`
}

const manager = wx.getBackgroundAudioManager()
// 存储播放的歌曲信息
let audioData = {
    src: '',
    title: '音频',
    duration: 0,
    startTime: 0
}
let audioInterval
// 是否需要重置数据
let resetAuido = true

/**-----------全局数据 */
const init = (e, t) => { // 初始化播放器
    if (!e.src || !e.title) {
        return
    }
    audioData.src = e.src || ''
    audioData.title = e.title || ''
    audioData.startTime = e.startTime || ''
    resetAuido = true
}

const createAudio = (e, t) => {
    console.log(e);
    if (!e.src) {
        alert('没有音频地址')
        return
    }
    console.log('进入了createAudio方法');
    setAudio(e, t)
    clearInterval(audioInterval)
    audioInterval = setInterval(() => {
        let backgroundAudio = t.data.backgroundAudio
        backgroundAudio.isPlaying = !manager.paused
        t.setData({
            backgroundAudio
        })
        if (!manager.paused) {
            let e = {
                currentTime: manager.currentTime
            }
            changeAudioProgressBar(e, t)
        }
    }, 1000)
    manager.onError((e) => {
        console.log(e, '播放错误');
    })
    manager.onEnded(() => {
        resetAuido = true
        let e = {
            progress: 0
        }
        changeAudioProgressBar(e, t)
        pause(t)
    })
}

const getDuration = (e, t) => {
    if (!e.src) {
        return
    }
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = e.src
    innerAudioContext.play()
    innerAudioContext.pause()
    innerAudioContext.onCanplay(() => {
        var durationInterval = setInterval(() => {
            if (innerAudioContext.duration) {
                audioData.duration = innerAudioContext.duration
                let backgroundAudio = t.data.backgroundAudio
                backgroundAudio.duration = innerAudioContext.duration
                console.log('播放时长', backgroundAudio.duration)
                var min = parseInt(innerAudioContext.duration / 60), sec = parseInt(innerAudioContext.duration % 60);
                //小程序无法使用padstart，采用以下方式补全时间格式
                if (min.toString().length == 1) {
                    min = `0${min}`
                } else {
                    min = `${min}`
                }
                if (sec.toString().length == 1) {
                    sec = `0${sec}`
                } else {
                    sec = `${sec}`
                }
                backgroundAudio.durationTime = `${min}:${sec}`;
                t.setData({
                    backgroundAudio
                })
                clearInterval(durationInterval)
            }
        }, 1000);

    })

}

const changeAudioProgressBar = (e, t) => { // 进度条改变事件

    console.log("进入了滚动条的变化事件");
    let duration, currentDuration, currentDurationTime, progress
    duration = manager.duration

    if (e.currentTime || e.currentTime == 0) {
        currentDuration = e.currentTime
        progress = parseInt(100 * currentDuration / duration)
    } else {
        progress = e.progress
        currentDuration = parseInt(progress * duration / 100)
    }
    let timeArr = [parseInt(duration / 60), parseInt(duration % 60), parseInt(currentDuration / 60), parseInt(currentDuration % 60)];
    for (let i in timeArr) {
        //小程序无法使用padstart，采用以下方式补全时间格式
        if (timeArr[i].toString().length == 1) {
            timeArr[i] = `0${timeArr[i]}`
        } else {
            timeArr[i] = `${timeArr[i]}`
        }
    }
    currentDurationTime = `${timeArr[2]}:${timeArr[3]}`;
    let backgroundAudio = t.data.backgroundAudio
    backgroundAudio.currentTime = currentDuration
    backgroundAudio.currentDurationTime = currentDurationTime
    backgroundAudio.progress = progress
    console.log(t.data.backgroundAudio.progress,"看看视频的进度变了没有");
    t.setData({ backgroundAudio })
    return backgroundAudio
}

const play = (t) => { // 播放
    if (resetAuido) {
        // 
        console.log('进入了play的方法');
        let e = {
            src: audioData.src,
            title: audioData.title,
            startTime: audioData.startTime
        }
        createAudio(e, t)
    }
    manager.play()
    if (t) {
        t.setData({
            'backgroundAudio.isPlaying': true
        })
    }
}

const pause = (t) => { // 暂停
    manager.pause()
    if (t) {
        let backgroundAudio = t.data.backgroundAudio
        backgroundAudio.isPlaying = false
        t.setData({
            backgroundAudio
        })
    }
}

const stop = (t) => { // 结束
    manager.stop()
    if (t) {
        let backgroundAudio = t.data.backgroudAudio
        backgroundAudio.isPlaying = false
        t.setData({
            backgroundAudio
        })
    }
}

const uninstall = (t) => {
    stop()
    clearInterval(audioInterval)
    audioData = {
        src: '',
        title: ''
    }
    resetAuido = true
}

const setAudio = (e, t) => {
    if (!e.src) {
        alert('没有音频地址')
        return
    }
    console.log('进入了setAudio方法');
    manager.src = e.src;
    manager.title = e.title;
    manager.startTime = e.startTime;
    audioData.src = e.src;
    audioData.title = e.title
    resetAuido = false
    pause(t)
}



const seek = (e, t) => { // 跳转到该进度播放
    console.log('seek事件触发了');
    if (resetAuido) {
        if (e.currentTime || e.currentTime == 0) {
            audio.startTime = e.currentTime
        } else {
            audioData.startTime = parseInt(e.progress * audio.duration / 100)
        }
    } else {

        if (e.currentTime || e.currentTime == 0) {
            manager.seek(parseInt(e.currentTime))
        } else {
            manager.seek(parseInt(e.progress * manager.duration / 100))
        }
        if (!manager.paused) {
            play(t)
        } else {
            pause(t)
        }

    }

}
Component({
    /**
     * 组件的属性列表 --  父子组件传值写到这
     */
    properties: {
        audioSrc: {
            type: String
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        playBtn: "https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/playBtn.png", //播放按钮
        pauseBtn: "https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/pages/pauseBtn.png",//暂停按钮
        backgroundAudio: {// 在播放的过程中会先创建一个 backgroundAudioManager 对象
            title: '', // 标题
            src: '',  // 文件路径
            currentDurationTime: '', // 格式化的时间
            durationTime: '', // 播放的总时长
            cuttentTime: '',//当前播放时长
            currentDurationTime: '',
            progress: "",//进度
            isPlaying: false
        },
        audio: { // 用来存储服务器传输过来的内容
            src: "",
            title: '标题'
        }
    },

    // 生命周期函数
    lifetimes: {
        // 测试从父组件能不能拿到音频的url
        attached () {
            setTimeout(() => {
                console.log(this.data.audioSrc, '音频的url')
                // 初始化接收父组件传递过来的值
                const src = this.data.audioSrc
                audioData.src = src
                this.setData({
                    'audio.src': src
                })
                // 初始化播放
                this.initBackGroundAudio()
            }, 1000)

        },
        detached(){
            uninstall(this)
        }
    },


    /**
     * 组件的方法列表
     */

    methods: {
 
        initBackGroundAudio () {
            console.log(12);
            if (!this.data.audio.src) {
                return
            }
            let audio = {//设置播放器属性，src与title为必填
                src: this.data.audio.src,
                title: this.data.audio.title,
            };
            init(audio, this);//初始化audio
            getDuration(audio, this);//获取视频长度
            pause(this);//暂停播放
        },
        dragAudioSlider (e) {//拖动进度条
            console.log(e,"进度条的值");
            seek({
                progress: e.detail.value
            }, this)//跳转到该进度
            play(this);//播放
        },
        playAudio () { // 播放||暂停
            console.log('点击了播放或者暂停');
            // debugger
            if (this.data.backgroundAudio.isPlaying) {
                pause(this)
            } else {
                play(this)
            }
        }

    }





})
